package com.example.amusic.viewmodel

import androidx.collection.mutableIntSetOf
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.media3.common.MediaItem
import com.example.amusic.service.CustomMediaServiceHandler
import com.example.amusic.service.MusicMediaState
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import java.util.concurrent.TimeUnit

sealed class UIState {
    object Initial : UIState()
    object Ready : UIState()
    object Ended : UIState()
}

class PlayViewModel : ViewModel() {

    private var _recreateActivity: MutableLiveData<Boolean> = MutableLiveData()
    val recreateActivity: LiveData<Boolean> = _recreateActivity

    var customMediaServiceHandler: CustomMediaServiceHandler? = null
    private var initJob: Job? = null

    var isPlaying = MutableStateFlow<Boolean>(false)
    var notReady = MutableLiveData<Boolean>(true)

    private val _uiState = MutableStateFlow<UIState>(UIState.Initial)
    val uiState = _uiState.asStateFlow()

    private var _bufferedPercentage = MutableStateFlow<Int>(0)
    val bufferedPercentage: SharedFlow<Int> = _bufferedPercentage.asSharedFlow()

    private val _duration = MutableStateFlow<Long>(0L)
    val duration: SharedFlow<Long> = _duration.asSharedFlow()

    private var _progressMillis = MutableStateFlow<Long>(0L)
    val progressMillis: SharedFlow<Long> = _progressMillis.asSharedFlow()

    private var _progress = MutableStateFlow<Float>(0F)
    val progress: SharedFlow<Float> = _progress.asSharedFlow()

    private var _progressString: MutableStateFlow<String> = MutableStateFlow("00:00")
    val progressString: SharedFlow<String> = _progressString.asSharedFlow()

    fun activityRecreate() {
        _recreateActivity.value = true
    }

    fun activityRecreateDone() {
        _recreateActivity.value = false
    }

    fun init() {
        //监听收集数据
        initJob =
            viewModelScope.launch {
                val job1 = launch {
                    customMediaServiceHandler!!.musicMediaState.collect { musicMediaState ->
                        when (musicMediaState) {
                            is MusicMediaState.Buffering -> {
                                notReady.value = true
                            }

                            MusicMediaState.Ended -> _uiState.value = UIState.Ended
                            MusicMediaState.Initial -> _uiState.value = UIState.Initial
                            is MusicMediaState.Loading -> {
                                _bufferedPercentage.value = musicMediaState.bufferedPercentage
                                _duration.value = musicMediaState.duration
                            }

                            is MusicMediaState.Playing -> {
                                isPlaying.value = musicMediaState.isPlaying
                            }

                            is MusicMediaState.Progress -> {
                                if (_duration.value > 0) {
                                    calculateProgressValues(musicMediaState.progress)
                                    _progressMillis.value = musicMediaState.progress
                                }
                            }

                            is MusicMediaState.Ready -> {
                                notReady.value = false
                                _duration.value = musicMediaState.duration
                                calculateProgressValues(customMediaServiceHandler!!.getProgress())
                                _uiState.value = UIState.Ready
                            }
                        }
                    }
                }
                job1.join()
            }
    }

    fun playAll(songList: List<MediaItem>, song: MediaItem){
        customMediaServiceHandler?.let {
            it.player.stop()
            it.player.setMediaItems(songList)
            it.play(song.mediaId)
            player.seekTo(index, 0)
            player.prepare()
        }
    }

    private fun calculateProgressValues(currentProgress: Long) {
        _progress.value =
            if (currentProgress > 0) (currentProgress.toFloat() / _duration.value) else 0f
        _progressString.value = formatDuration(currentProgress)
    }

    private fun formatDuration(duration: Long): String {
        val minutes: Long = TimeUnit.MINUTES.convert(duration, TimeUnit.MILLISECONDS)
        val seconds: Long = (
                TimeUnit.SECONDS.convert(duration, TimeUnit.MILLISECONDS) -
                        minutes * TimeUnit.SECONDS.convert(1, TimeUnit.MINUTES)
                )
        return String.format("%02d:%02d", minutes, seconds)
    }
}